package com.qfedu.boot.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.Random;

public class AliSmsUtil {

    private static Client client;
    /**下面的密钥不能泄漏*/
    private static String accessKeyId="LTAI5t6FH3pZxn3x1sLPYYDz";
    private static String accessKeySecret="DtAFYG8laPbt5mo3djH83ahIi10voz";


    static {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client=new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @param phone 手机号
     * @param code 验证码
     * @return 发送是否成功*/
    public static boolean sendSms(String phone,int code) {
        SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("来自邢朋辉的短信")
                .setTemplateCode("SMS_115250125")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse response=client.sendSmsWithOptions(request, runtime);
            return response.body.getCode().equals("OK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 生成随机验证码
     * @param len 长度*/
    public static int createCode(int len){
        //4位 验证码 1000-9999 0-8999-9000  9000
        //6位 100000-999999 100000 0-900000
        Random random=new Random();
        int l=(int)Math.pow(10,len-1);
        return l+random.nextInt((int)(Math.pow(10,len)-l));
    }
    /**
     * 生成验证码  字符串类型*/
    public static String createStrCode(int len){
        //4位 验证码 1000-9999 0-8999-9000  9000
        //6位 100000-999999 100000 0-900000
        Random random=new Random();
        StringBuffer buffer=new StringBuffer();
        for (int i = 0; i < len; i++) {
            buffer.append(random.nextInt(10));
        }
        return buffer.toString();
    }
}
